package com.xique.door.device.freeview.service.biz;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xique.common.core.enums.StatusCode;
import com.xique.common.core.utils.AliossUtil;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.MD5Util;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.domain.estate.EstateUserDevice;
import com.xique.door.bean.search.UserDeviceSearch;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.device.freeview.bean.dto.FreeviewUserInfoDto;
import com.xique.door.device.freeview.bean.request.advertisement.UpdatePlayPolicyGetStateInfomation;
import com.xique.door.device.freeview.bean.request.advertisement.UpdatePlayPolicyGetStateRequest;
import com.xique.door.device.freeview.bean.request.card.ConfirmCardsSyncedDetailRequest;
import com.xique.door.device.freeview.bean.request.card.ConfirmCardsSyncedRequest;
import com.xique.door.device.freeview.bean.request.card.GetCardsInfoRequest;
import com.xique.door.device.freeview.bean.request.face.ConfirmFaceRecognitionsSyncedDetailRequest;
import com.xique.door.device.freeview.bean.request.face.ConfirmFaceRecognitionsSyncedRequest;
import com.xique.door.device.freeview.bean.request.face.FaceRecognitionsInfoRequest;
import com.xique.door.device.freeview.bean.vo.card.GetCarDetaiVo;
import com.xique.door.device.freeview.bean.vo.card.GetCardVo;
import com.xique.door.device.freeview.bean.vo.card.GetCardsInfoVo;
import com.xique.door.device.freeview.bean.vo.face.FaceRecognitionsDetaiVo;
import com.xique.door.device.freeview.bean.vo.face.FaceRecognitionsInfoVo;
import com.xique.door.device.freeview.bean.vo.face.FaceRecognitionsVo;
import com.xique.door.device.freeview.constant.*;
import com.xique.door.service.*;
import com.xique.door.service.estate.IEstateUserDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: caogangquan
 * @Date: 2021/10/13 16:49
 * @Description:
 */
@Service
@Slf4j
public class FreeviewBizService {

    @Autowired
    private FreeviewEventBizService freeviewEventBizService;

    @Autowired
    private AliossUtil aliossUtil;

    @Autowired
    private FreeviewCommandBizService freeviewCommandBizService;

    @Autowired
    private IUserDeviceService userDeviceService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBuildHouseUserService houseUserService;

    @Autowired
    private IVisitorDeviceService visitorDeviceService;

    @Autowired
    private IDCardDeviceService cardDeviceService;

    @Autowired
    private IDDeviceAdvertService deviceAdvertService;

    @Autowired
    private IBuildingDeviceService buildingDeviceService;

    @Autowired
    private IEstateUserDeviceService estateUserDeviceService;

    //------------------------------------------------人脸start-------------------------------------------------

    /**
     * @description: step1：获取人脸同步数据
     * @author caogq
     * @date 2021/11/4 10:56
     * @version 1.0
     */
    public FaceRecognitionsVo getFaceRecognitions(String eventId) {
        Long eventType = freeviewEventBizService.getEventTypeByEventId(eventId);

        List<FreeviewUserInfoDto> users = freeviewEventBizService.getUserParamByEventId(eventId);

        FaceRecognitionsVo faceRecognitionsVo = new FaceRecognitionsVo();
        faceRecognitionsVo.setEventId(eventId);
        //无用字段
        faceRecognitionsVo.setRemainder(0);
        List<FaceRecognitionsDetaiVo> detaiVos = new ArrayList<>();
        for (FreeviewUserInfoDto user : users) {
            FaceRecognitionsDetaiVo faceRecognitionsDetaiVo = new FaceRecognitionsDetaiVo();
            faceRecognitionsDetaiVo.setFeatureUniqueID(user.getCustomId());
            if (FreeViewConstant.EventType.DELETE_SINGLE_PERSON.equals(eventType) || FreeViewConstant.EventType.DELETE_MULTIPLE_PERSON.equals(eventType) || FreeViewConstant.EventType.DELETE_VISITOR.equals(eventType)) {
                //删除
                faceRecognitionsDetaiVo.setOperationType(2);
            } else {
                //新增
                faceRecognitionsDetaiVo.setOperationType(1);
            }
            //无用字段
            faceRecognitionsDetaiVo.setFileHashCode("123");
            //无用字段
            faceRecognitionsDetaiVo.setFileSize(49028);
            faceRecognitionsDetaiVo.setUrl(user.getFaceUrl());
            detaiVos.add(faceRecognitionsDetaiVo);
        }
        faceRecognitionsVo.setHumanFeatures(detaiVos);
        return faceRecognitionsVo;
    }

    public Map<String, Object> getBaseResponseMap(String code) {
        Map<String, Object> map = new HashMap<>();
        switch (code) {
            case "success":
                map.put("errorCode", 0);
                map.put("errorMsg", "success");
                break;
            case "failure":
                map.put("errorCode", 500);
                map.put("errorMsg", "error");
                break;
            default:
        }
        return map;

    }

    /**
     * @description: step2：获取人脸详细详细
     * @author caogq
     * @date 2021/11/4 10:56
     * @version 1.0
     */
    public Map<String, Object> getFaceRecognitionsInfo(FaceRecognitionsInfoRequest request) {
        List<FreeviewUserInfoDto> users = freeviewEventBizService.getUserParamByEventId(request.getEventID());

        List<String> featureUniqueIds = request.getFeatureUniqueIds();
        List<FaceRecognitionsInfoVo> list = new ArrayList<>();

        for (String featureUniqueId : featureUniqueIds) {
            FreeviewUserInfoDto user = users.stream().filter(e -> e.getCustomId().equals(featureUniqueId)).findFirst().get();
            FaceRecognitionsInfoVo faceRecognitionsInfoVo = new FaceRecognitionsInfoVo();
            faceRecognitionsInfoVo.setFeatureUniqueID(featureUniqueId);
            faceRecognitionsInfoVo.setPeopleName(user.getUserName());
            faceRecognitionsInfoVo.setPaperType(1);
            faceRecognitionsInfoVo.setPeopleType(user.getPeopleType());
            faceRecognitionsInfoVo.setPaperNo(user.getCustomId());
            faceRecognitionsInfoVo.setAuthorizationTime(DateUtils.getCurrentUTCTimestamp());
            faceRecognitionsInfoVo.setValidTimeType(user.getValidTimeType());
            faceRecognitionsInfoVo.setValidStartTime(user.getValidStartTime());
            faceRecognitionsInfoVo.setValidEndTime(user.getValidEndTime());
            faceRecognitionsInfoVo.setMaxValidTimes(10);
            faceRecognitionsInfoVo.setIsEnable(1);
            faceRecognitionsInfoVo.setIsDisable(false);
//            faceRecognitionsInfoVo.setRoomLocation("0101,0201,0301,0401,0501,0601,0701,0801,0901,1001,1101,1201,1301,1401,1501,1601");
            faceRecognitionsInfoVo.setRoomLocation(user.getRoomLocation());
            list.add(faceRecognitionsInfoVo);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);

        return map;
    }

    /**
     * @description: 返回人脸下发结果
     * @author caogq
     * @date 2021/11/4 10:58
     * @version 1.0
     */

    public Map<String, Object> confirmFaceRecognitionsSynced(ConfirmFaceRecognitionsSyncedRequest request, String devSn) {
        //响应结果-新增用户
        List<ConfirmFaceRecognitionsSyncedDetailRequest> downUserResponse = request.getHumanFeatures().stream().filter(e -> CommandOperationType.DOWN == e.getOperationType()).collect(Collectors.toList());
        //响应结果-删除用户
        List<ConfirmFaceRecognitionsSyncedDetailRequest> deleteUserResponse = request.getHumanFeatures().stream().filter(e -> CommandOperationType.DELETE == e.getOperationType()).collect(Collectors.toList());
        List<String> delCustomIdList = new ArrayList<>();
        List<String> downSucCustomIdList = new ArrayList<>();
        List<String> downFailCustomIdList = new ArrayList<>();

        if (!downUserResponse.isEmpty()) {
            //默认下发状态为2 成功
            Long recordStatus = DoorEventStatus.SUCCESS;
            //1、成功 2、失败
            StringBuilder errorStringBuilder = new StringBuilder("下发失败，具体信息如下：");
            for (ConfirmFaceRecognitionsSyncedDetailRequest humanFeature : downUserResponse) {
                if (humanFeature.getOperationResult() != null && humanFeature.getOperationResult().equals(OperationResult.FAILURE)) {
                    recordStatus = DoorEventStatus.FAILURE;
                    //有一个人员下发失败,则认为此事件是下发失败
                    errorStringBuilder.append("人员编号：" + humanFeature.getFeatureUniqueID() + ",失败原因：" + humanFeature.getErrorMessage() + "；");
                    downFailCustomIdList.add(humanFeature.getFeatureUniqueID());
                } else {
                    //下发成功
                    downSucCustomIdList.add(humanFeature.getFeatureUniqueID());
                }
            }
            freeviewEventBizService.updateEventStatus(request.getEventId(), recordStatus, DoorEventStatus.SUCCESS.equals(recordStatus) ? "下发成功" : errorStringBuilder.toString());
        }

        if (!deleteUserResponse.isEmpty()) {
            //默认下发状态为2 成功
            Long recordStatus = DoorEventStatus.SUCCESS;
            //1、成功 2、失败
            StringBuilder errorStringBuilder = new StringBuilder("删除失败，具体信息如下：");
            for (ConfirmFaceRecognitionsSyncedDetailRequest humanFeature : deleteUserResponse) {
                if (humanFeature.getOperationResult() != null && humanFeature.getOperationResult().equals(OperationResult.FAILURE)) {
                    //有人员下发失败,则认为此事件是下发失败
                    recordStatus = DoorEventStatus.FAILURE;
                    errorStringBuilder.append("人员编号：" + humanFeature.getFeatureUniqueID() + ",失败原因：" + humanFeature.getErrorMessage() + "；");
                    downFailCustomIdList.add(humanFeature.getFeatureUniqueID());
                    continue;
                }
                //删除用户成功，删除中间表数据
                delCustomIdList.add(humanFeature.getFeatureUniqueID());
            }
            //事件结果回填
            freeviewEventBizService.updateEventStatus(request.getEventId(), recordStatus, DoorEventStatus.SUCCESS.equals(recordStatus) ? "删除成功" : errorStringBuilder.toString());
        }
        if (!delCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchDeleteUserDevice(delCustomIdList, devSn);
        }
        if (!downSucCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateUserCommandStatus(downSucCustomIdList, devSn, CommandStatus.SUCCESS);
        }
        if (!downFailCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateUserCommandStatus(downFailCustomIdList, devSn, CommandStatus.FAILURE);
        }

        // 更新访客状态
        if (!delCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateVisitorCommandStatus(delCustomIdList, devSn, CommandStatus.DELETE);
        }
        if (!downSucCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateVisitorCommandStatus(downSucCustomIdList, devSn, CommandStatus.SUCCESS);
        }
        if (!downFailCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateVisitorCommandStatus(downFailCustomIdList, devSn, CommandStatus.FAILURE);
        }

        // 更新物业人员状态
        if (!delCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateEstateUserCommandStatus(delCustomIdList, devSn, CommandStatus.DELETE);
        }
        if (!downSucCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateEstateUserCommandStatus(downSucCustomIdList, devSn, CommandStatus.SUCCESS);
        }
        if (!downFailCustomIdList.isEmpty()) {
            //设备返回删除成功列表，删除记录
            this.batchUpdateEstateUserCommandStatus(downFailCustomIdList, devSn, CommandStatus.FAILURE);
        }

        Map<String, Object> baseResponseMap = getBaseResponseMap("success");
        baseResponseMap.put("data", true);
        return baseResponseMap;
    }

    public int batchUpdateUserCommandStatus(List<String> customIdList, String devSn, String status) {
        UserDeviceSearch userDeviceSearch = new UserDeviceSearch();
        userDeviceSearch.setCustomIds(customIdList);
        userDeviceSearch.setDevSn(devSn);
        List<UserDevice> existUserDevices = userDeviceService.selectUserDeviceListBySearch(userDeviceSearch);
        if (CollectionUtils.isEmpty(existUserDevices)) {
            return 1;
        }
        for (UserDevice existUserDevice : existUserDevices) {
            existUserDevice.setUpdateTime(new Date());
            existUserDevice.setStatus(status);
        }
        return userDeviceService.batchUpdateUserDevice(existUserDevices);
    }


    public int batchDeleteUserDevice(List<String> customIdList, String devSn) {
        UserDeviceSearch userDeviceSearch = new UserDeviceSearch();
        userDeviceSearch.setCustomIds(customIdList);
        userDeviceSearch.setDevSn(devSn);
        List<UserDevice> existUserDevices = userDeviceService.selectUserDeviceListBySearch(userDeviceSearch);
        if (CollectionUtils.isEmpty(existUserDevices)) {
            return 1;
        }
        return userDeviceService.batchDeleteUserDevice(existUserDevices.stream().map(UserDevice::getId).collect(Collectors.toList()));
    }

    private boolean batchUpdateVisitorCommandStatus(List<String> customIdList, String devSn, String status) {
        QueryWrapper<VisitorDevice> condition = new QueryWrapper<>();
        condition.eq("dev_sn", devSn);
        condition.in("custom_id", customIdList);
        List<VisitorDevice> list = visitorDeviceService.list(condition);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        list.forEach(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(status);
        });
        return visitorDeviceService.updateBatchById(list);
    }


    private boolean batchDeleteVisitorDevice(List<String> customIdList, String devSn) {
        QueryWrapper<VisitorDevice> condition = new QueryWrapper<>();
        condition.eq("dev_sn", devSn);
        condition.in("custom_id", customIdList);
        List<VisitorDevice> list = visitorDeviceService.list(condition);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        return visitorDeviceService.removeByIds(list.stream().map(VisitorDevice::getId).collect(Collectors.toList()));
    }

    private boolean batchUpdateEstateUserCommandStatus(List<String> customIdList, String devSn, String status) {
        QueryWrapper<EstateUserDevice> condition = new QueryWrapper<>();
        condition.eq("dev_sn", devSn);
        condition.in("custom_id", customIdList);
        List<EstateUserDevice> list = estateUserDeviceService.list(condition);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        list.forEach(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(status);
        });
        return estateUserDeviceService.updateBatchById(list);
    }

    //------------------------------------------------card-start-------------------------------------------------

    /**
     * @description: step1：获取卡同步数据
     * @author caogq
     * @date 2021/11/4 11:00
     * @version 1.0
     */

    public GetCardVo getCards(String eventId) {
        //FreeviewDeviceCardInfoDto
        List<GetCardsInfoVo> cardsInfoVos = freeviewEventBizService.getCardParamByEventId(eventId, GetCardsInfoVo.class);
        GetCardVo getCardVo = new GetCardVo();
        getCardVo.setEventId(eventId);
        getCardVo.setRemainder(0);
        List<GetCarDetaiVo> cardDetailList = new ArrayList<>();
        for (GetCardsInfoVo cardsInfoVo : cardsInfoVos) {
            GetCarDetaiVo cardDetail = new GetCarDetaiVo();
            cardDetail.setCardId(cardsInfoVo.getCardId());
            cardDetail.setCardNo(cardsInfoVo.getCardNo());
            cardDetail.setOperationType(cardsInfoVo.getOperationType());

            cardDetailList.add(cardDetail);
        }
        getCardVo.setCards(cardDetailList);
        return getCardVo;
    }


    /**
     * @description: step2：获取卡片
     * @author caogq
     * @date 2021/11/4 11:01
     * @version 1.0
     */

    public Object getCardsInfo(GetCardsInfoRequest request) {
        List<GetCardsInfoVo> cardsInfoVos = freeviewEventBizService.getCardParamByEventId(request.getEventId(), GetCardsInfoVo.class);
        Map<String, Object> map = new HashMap<>();
        map.put("list", cardsInfoVos);
        return map;
    }

    /**
     * @description: step3，返回卡同步消息
     * @author caogq
     * @date 2021/11/4 11:01
     * @version 1.0
     */
    @Transactional
    public Map<String, Object> confirmCardsSynced(ConfirmCardsSyncedRequest request, String devSn) {
        List<ConfirmCardsSyncedDetailRequest> downCardResponse = request.getCards().stream().filter(e -> CommandOperationType.DOWN == e.getOperationType()).collect(Collectors.toList());
        List<ConfirmCardsSyncedDetailRequest> deleteCardResponse = request.getCards().stream().filter(e -> CommandOperationType.DELETE == e.getOperationType()).collect(Collectors.toList());

        List<String> delCardIdList = new ArrayList<>();
        List<String> downSucCardIdList = new ArrayList<>();
        List<String> downFailCardIdList = new ArrayList<>();

        if (!downCardResponse.isEmpty()) {
            Long recordStatus = DoorEventStatus.SUCCESS;
            StringBuilder errorStringBuilder = new StringBuilder("下发失败，具体信息如下：");
            for (ConfirmCardsSyncedDetailRequest response : downCardResponse) {
                if (response.getOperationResult() != null && response.getOperationResult().equals(OperationResult.FAILURE)) {
                    recordStatus = DoorEventStatus.FAILURE;
                    //有人员下发失败,则认为此事件是下发失败
                    errorStringBuilder.append("卡号：" + response.getCardId() + ",失败原因：" + response.getErrorMessage() + "；");
                    downFailCardIdList.add(response.getCardId());
                } else {
                    downSucCardIdList.add(response.getCardId());
                }
            }
            freeviewEventBizService.updateEventStatus(request.getEventId(), recordStatus, DoorEventStatus.SUCCESS.equals(recordStatus) ? "下发成功" : errorStringBuilder.toString());
        }

        if (!deleteCardResponse.isEmpty()) {
            Long recordStatus = DoorEventStatus.SUCCESS;
            StringBuilder errorStringBuilder = new StringBuilder("删除失败，具体信息如下：");
            for (ConfirmCardsSyncedDetailRequest response : deleteCardResponse) {
                if (response.getOperationResult() != null && response.getOperationResult().equals(OperationResult.FAILURE)) {
                    //有人员下发失败,则认为此事件是下发失败
                    recordStatus = DoorEventStatus.FAILURE;
                    errorStringBuilder.append("卡号：" + response.getCardId() + ",失败原因：" + response.getErrorMessage() + "；");
                    downFailCardIdList.add(response.getCardId());
                } else {
                    delCardIdList.add(response.getCardId());
                }
            }
            //事件结果回填
            freeviewEventBizService.updateEventStatus(request.getEventId(), recordStatus, DoorEventStatus.SUCCESS.equals(recordStatus) ? "下发成功" : errorStringBuilder.toString());
        }

        if (!delCardIdList.isEmpty()) {
            this.batchDeleteCard(delCardIdList, devSn);
        }
        if (!downSucCardIdList.isEmpty()) {
            this.batchUpdateCardCommandStatus(downSucCardIdList, devSn, CommandStatus.SUCCESS);
        }
        if (!downFailCardIdList.isEmpty()) {
            this.batchUpdateCardCommandStatus(downFailCardIdList, devSn, CommandStatus.FAILURE);
        }

        Map<String, Object> baseResponseMap = getBaseResponseMap("success");
        baseResponseMap.put("data", true);
        return baseResponseMap;
    }

    private int batchUpdateCardCommandStatus(List<String> cardSns, String devSn, String status) {
        CardDevice search = new CardDevice();
        if (cardSns!= null && cardSns.size() == 1){
            search.setCardSn(cardSns.get(0));
        }else {
            search.setCardSns(cardSns);
        }
        search.setDevSn(devSn);
        List<CardDevice> cardDevices = cardDeviceService.selectDCardDeviceList(search);
        for (CardDevice cardDevice : cardDevices) {
            cardDevice.setStatus(status);
            cardDevice.setUpdateTime(new Date());
        }
        return cardDeviceService.batchUpdateCardDevice(cardDevices);
    }

    private int batchDeleteCard(List<String> delCardIdList, String devSn) {
        CardDevice cardDevice = new CardDevice();
        cardDevice.setCardSns(delCardIdList);
        cardDevice.setDevSn(devSn);
        List<CardDevice> cardDevices = cardDeviceService.selectDCardDeviceList(cardDevice);
        int i = cardDeviceService.deleteDCardDeviceByIds(cardDevices.stream().map(CardDevice::getId).collect(Collectors.toList()));
//        if (i < 0) {
//            return 0;
//        }
//        DCard card = new DCard();
//        card.setCardSns(delCardIdList);
//        List<DCard> dCards = cardService.selectCardList(card);
//        List<Long> cardIds = dCards.stream().map(DCard::getId).collect(Collectors.toList());
//        return cardService.deleteDCardByIdList(cardIds);
        return i;
    }


    //------------------------------------------------广告start-------------------------------------------------

    /**
     * 获取广告公告
     *
     * @param eventId
     * @return
     */
    public Object getAdvertisements(String eventId) {
//        Map<String, Object> map = new HashMap<>();
//        List<AdvertisementDto> advertisements = new ArrayList<>();
////        AdvertisementDto advertisementVo = new AdvertisementDto();
////        advertisements.add(advertisementVo);
////        advertisementVo.setFileSendId("74facc74f52a4ff08bc5aee5483e6c23");
//////        advertisementVo.setIntervalTime(10);
////        advertisementVo.setInformationId(21);
//////        advertisementVo.setInformationTitle("v1_lezhu2");
////        advertisementVo.setFileType(2);
////        advertisementVo.setFileName("乐主-人行广告门~2.mp4");
////        advertisementVo.setFileAddress("https://xqcloud.oss-cn-zhangjiakou.aliyuncs.com/dev/freeview/2.mp4");
////
//////        advertisementVo.setFileSize(null);
//////        advertisementVo.setFileHashCode("");
//////        advertisementVo.setInformationContent("");
////        advertisementVo.setValidTimeType(1);
////        advertisementVo.setValidTimeStart(1647002200L);
////        advertisementVo.setValidTimeEnd(1848634870L);
////        advertisementVo.setPlayOrder(1);
//////        advertisementVo.setIsMonopoly(0);
////        advertisementVo.setOperateType(2);
//
//        AdvertisementDto advertisementDto2 = new AdvertisementDto();
//        advertisements.add(advertisementDto2);
//        //必填
//        advertisementDto2.setFileSendId("74facc74f52a4ff08bc5aee5483e6c22");
//        //jpg格式的广告，切换时间
////        advertisementDto2.setIntervalTime(10);
//        advertisementDto2.setInformationId(22);
////        advertisementDto2.setInformationTitle("v1_lezhu2");
//        advertisementDto2.setFileType(2);
//        //必填
//        advertisementDto2.setFileName("乐主-人行广告门~3.mp4");
//        advertisementDto2.setFileAddress("https://xqcloud.oss-cn-zhangjiakou.aliyuncs.com/freeview/1634871801904755.mp4");
////        advertisementDto2.setFileSize(1L);
////        advertisementDto2.setFileHashCode("");
////        advertisementDto2.setInformationContent("");
//        advertisementDto2.setValidTimeType(1);
//        advertisementDto2.setValidTimeStart(1647002300L);
//        advertisementDto2.setValidTimeEnd(1948634870L);
//        advertisementDto2.setPlayOrder(1);
//        //没啥用
////        advertisementDto2.setIsMonopoly(0);
//        advertisementDto2.setOperateType(2);
//        map.put("list", advertisements);
//        return map;
        Object param = freeviewEventBizService.getEventParamByEventId(eventId);
        return param;
    }


    /**
     * @description: 临时密码验证
     * @author caogq
     * @date 2021/11/4 11:02
     * @version 1.0
     */

    public Object verifyPassword(String eventId, String password, String devSn) {

        Map<String, Object> result = new HashMap<>();

        log.info("临时密码验证Q1:==============> 密码:{}，设备:{}", password, devSn);

        AccessDevice device = accessDeviceService.selectAccessDeviceBySn(devSn);
        Long parkId = device.getParkId();

        User search = new User();
        search.setParkId(parkId);
        search.setInvitationCode(password);
        List<User> list = userService.selectUserList(search);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        User user = list.get(0);
        log.info("临时密码验证Q2:==============> 用户信息:{}", user);

        BuildingDevice buildingDeviceSearch = new BuildingDevice();
        buildingDeviceSearch.setDeviceId(device.getId());
        List<BuildingDevice> buildingDeviceList = buildingDeviceService.selectBuildingDeviceList(buildingDeviceSearch);
        List<Long> buildingIds = buildingDeviceList.stream().map(BuildingDevice::getBuildingId).distinct().collect(Collectors.toList());

        String code = houseUserService.selectFreeviewHouseCodeByUserIdV1(user.getId().toString(), buildingIds);

        log.info("临时密码验证Q3:==============> code:{}", code);

        if (StringUtils.isEmpty(code)) {
            return new ResponseEntity<>("Full authentication is required to access this resourceunauthorized.", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("operator", user.getUserName());
        map.put("extra", code);

        log.info("临时密码验证Q4:==============> map:{}", map);

        return map;
    }


    public AjaxResult freeviewUpgrade(String devSn, MultipartFile file) {
        AccessDevice accessDevice = new AccessDevice();
        accessDevice.setDevSn(devSn);
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
        if (accessDeviceList.isEmpty() && Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_45,AccessCommandConstant.DeviceType.FREEVIEW_32).contains(accessDeviceList.get(0).getModel())) {
            return AjaxResult.error("请选择全视通设备进行升级！");
        }
        //1、文件上传阿里云返回路径
        Map<String, Object> map = aliossUtil.uploadFreeviewUpgradeFile(file);
        if (map.get("code").equals(StatusCode.ERROR.getCode())) {
            return AjaxResult.error();
        }
        String url = (String) map.get("url");
        //2、文件md5加密
        String md5 = MD5Util.getMD5ByFile(file);
        //3、给设备发升级通知
        Object object = freeviewCommandBizService.upgrade(devSn, url, md5);
        //4、返回命令下发成功
        log.info("固件地址: " + url + " ; md5：" + md5);
        return AjaxResult.success("固件升级命令已下发");
    }

    public AjaxResult freeviewUpgrade(String devSn, MultipartFile file,String url) {
        AccessDevice accessDevice = new AccessDevice();
        accessDevice.setDevSn(devSn);
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
        if (accessDeviceList.isEmpty() && Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_45,AccessCommandConstant.DeviceType.FREEVIEW_32).contains(accessDeviceList.get(0).getModel())) {
            return AjaxResult.error("请选择全视通设备进行升级！");
        }
//        //1、文件上传阿里云返回路径
//        Map<String, Object> map = aliossUtil.uploadFreeviewUpgradeFile(file);
//        if (map.get("code").equals(StatusCode.ERROR.getCode())) {
//            return AjaxResult.error();
//        }
//        String url = (String) map.get("url");
        //2、文件md5加密
        String md5 = MD5Util.getMD5ByFile(file);
        //3、给设备发升级通知
        Object object = freeviewCommandBizService.upgrade(devSn, url, md5);
        //4、返回命令下发成功
        log.info("固件地址: " + url + " ; md5：" + md5);
        return AjaxResult.success("固件升级命令已下发");
    }

    /**
     * @param devSn
     * @param rangeTimes
     * @description: 设置息屏
     * @author taojc
     * @date: 2022/9/2
     */
    public AjaxResult screenSaveTimesRange(String devSn,List<String> rangeTimes){
        AccessDevice accessDevice = new AccessDevice();
        accessDevice.setDevSn(devSn);
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceList(accessDevice);
        if (accessDeviceList.isEmpty() && Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32).contains(accessDeviceList.get(0).getModel())) {
            return AjaxResult.error("设备不存在");
        }
        Object object = freeviewCommandBizService.screenSave(devSn, rangeTimes);
        //4、返回命令下发成功
        log.info("设备设置屏息时间成功");
        return AjaxResult.success("设置屏息命令已下发");
    }


    public Object updatePlayPolicyGetState(UpdatePlayPolicyGetStateRequest request, String devSn) {
//        List<UpdatePlayPolicyGetStateInfomation> downResponse = request.getInformationList().stream().filter(e -> e.getOperationType().equals("1")).collect(Collectors.toList());
//        List<UpdatePlayPolicyGetStateInfomation> deleteResponse = request.getInformationList().stream().filter(e -> e.getOperationType().equals("1")).collect(Collectors.toList());
//        if (!downResponse.isEmpty()){
//            Long recordStatus = DoorEventStatus.SUCCESS;
//            StringBuilder errorStringBuilder = new StringBuilder("广告下发失败，具体信息如下：");
//            for (UpdatePlayPolicyGetStateInfomation response : downResponse) {
//                if (response.getOperationResult().equals(2)){
//                    recordStatus = DoorEventStatus.FAILURE;
//                    errorStringBuilder.append("卡号：" + response.getFileSendId() + ",失败原因：" + response.getErrorMessage() + "；");
//
//                }
//            }
//        }
//        if (!deleteResponse.isEmpty()){
//
//        }
        List<UpdatePlayPolicyGetStateInfomation> informationList = request.getInformationList();
        if (!informationList.isEmpty()) {
            //目前广告只存在单条下发的情况
            UpdatePlayPolicyGetStateInfomation response = informationList.get(0);
            //1:添加 2:删除 3:清空
            StringBuilder errorStringBuilder = new StringBuilder();
            if (response.getOperationType().equals(1)) {
                errorStringBuilder.append("下发广告失败，具体信息如下：");

            } else if (response.getOperationType().equals(2)) {
                errorStringBuilder.append("删除广告失败，具体信息如下：");

            } else if (response.getOperationType().equals(3)) {
                errorStringBuilder.append("清空广告失败，具体信息如下：");

            }
            errorStringBuilder.append("广告id：" + response.getFileSendId() + ",失败原因：" + response.getErrorMessage() + "；");

            //事件结果回填
            freeviewEventBizService.updateEventStatus(request.getEventID(), response.getOperationResult() == 1 ? DoorEventStatus.SUCCESS : DoorEventStatus.FAILURE,  response.getOperationResult() == 1 ?"下发成功" : errorStringBuilder.toString());

            DDeviceAdvert search = new DDeviceAdvert();
            search.setDevSn(devSn);
            search.setAdvertId(Long.valueOf(response.getFileSendId()));
            List<DDeviceAdvert> deviceAdverts = deviceAdvertService.selectDDeviceAdvertList(search);
            if (!deviceAdverts.isEmpty()) {
                DDeviceAdvert deviceAdvert = deviceAdverts.get(0);
                deviceAdvert.setStatus(response.getOperationResult() == 1 ? CommandStatus.SUCCESS : CommandStatus.FAILURE);
                int i = deviceAdvertService.updateDDeviceAdvert(deviceAdvert);
            }
        }
        return true;
    }
}
